# coding=utf-8
# author:xc
# datetime:2018/10/16 9:28
from . import api
from dbConnection.MysqlConn import Mysql
from app import util, upload_files
from flask import request
from app.MySession import MySession


@api.route('/api/user/poster', methods=['POST', 'GET'])
def api_user_poster():
    try:
        session = request.values.get("session", default="0")
        page = request.values.get('page', default=1)
        page = int(page)
        num = (page - 1) * util.PAGE_NUM
        if str(session) == "0":
            uid = 0
        else:
            uid = MySession.get_name(session)
        mysql = Mysql()
        sql = "select a.*,b.nickname,b.header,c.praise from girl_poster as a left join " \
              "girl_teacher as b on a.uid= b.uid left join (select * from girl_praise " \
              "where uid='%s') as c on a.posterId=c.posterId where a.status=1 order by a.addTime desc limit %d,%d" % (
                  uid, num, util.PAGE_NUM)
        sql1 = "select count(*) from girl_poster  where status=1 "
        sql2 = "select b.*,c.header,c.nickname,d.nickname as name from girl_poster as a " \
               "left join girl_poster_reply as b on a.posterId=b.posterId left join girl_teacher as" \
               " c on b.uid=c.uid left join girl_teacher as d on d.uid=b.f_uid  where " \
               "  b.status=1 order by b.addTime asc "
        result = mysql.getAll(sql, None)
        res = mysql.getAll(sql2, None)
        count = mysql.getOne(sql1, None)
        mysql.dispose()
        data = []
        code = util.CODE_EMPTY
        if count:
            count = count['count(*)']
            if count % util.PAGE_NUM > 0:
                max_page = count / util.PAGE_NUM + 1
            else:
                max_page = count / util.PAGE_NUM
        else:
            max_page = 0
        if result:
            code = util.CODE_SUCCESS
            for x in result:
                data_poster = dict()
                data_poster['posterId'] = x['posterId']
                data_poster['flag'] = x['flag']
                data_poster['content'] = x['content']
                if int(x['flag']) == 0:
                    data_poster['voiceUrl'] = ""
                    data_poster['videoUrl'] = ""
                    data_poster['imgUrl'] = ""
                elif int(x['flag']) == 1:
                    data_poster['voiceUrl'] = ""
                    data_poster['videoUrl'] = ""
                    urls = x['imgUrl'].split(',')
                    url_list = ''
                    for y in urls:
                        if not y.startswith("http"):
                            url_list += upload_files.baseUrl + y + ","
                        else:
                            url_list += y + ","
                    url_list = url_list[:-1]
                    data_poster['imgUrl'] = url_list
                data_poster['addTime'] = x['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                if x['praise'] is None or int(x['praise']) == 0:
                    data_poster['praise'] = 0
                else:
                    data_poster['praise'] = 1
                if not x['header'].startswith('http'):
                    data_poster['header'] = upload_files.baseUrl + x['header']
                else:
                    data_poster['header'] = x['header']
                data_poster['nickname'] = x['nickname']
                data_poster['praiseNum'] = x['praiseNum']
                reply = []
                if res:
                    for k in res:
                        if x['posterId'] == k['posterId']:
                            data_reply = dict()
                            data_reply['uid'] = k['uid']
                            data_reply['f_uid'] = k['f_uid']
                            if data_reply['f_uid'] == 0:
                                data_reply['name'] = ""
                            else:
                                data_reply['name'] = k['name']
                            data_reply['content'] = k['content']
                            data_reply['addTime'] = k['addTime'].strftime('%Y-%m-%d %H:%M:%S')
                            data_reply['nickname'] = k['nickname']
                            if not k['header'].startswith("http"):
                                data_reply['header'] = upload_files.baseUrl + k['header']
                            else:
                                data_reply['header'] = k['header']
                            reply.append(data_reply)
                data_poster['res'] = reply
                data.append(data_poster)
    except Exception as e:
        print e
        code = util.CODE_ERROR
        data = []
        max_page = 0
    data = {
        'data': data,
        'code': code,
        'max_page': max_page
    }
    return util.to_json(data)


